from datetime import timedelta

from django import forms
from django.core.exceptions import ValidationError

from firstplan import models
from firstplan.mine.mymd5 import mymd5


class MyForm:
    exclude_fields = []

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)

        for name,field in self.fields.items():
            if name in self.exclude_fields:
                continue
            if field.widget.attrs:
                field.widget.attrs['class'] = "form-control"
                field.widget.attrs['placeholder'] = field.label
            else:
                field.widget.attrs = {'class':"form-control",'placeholder':field.label}


class PlanList(MyForm,forms.ModelForm):
    class Meta:
        model = models.PlanEvent
        fields = '__all__'


class EverydayList(MyForm,forms.ModelForm):
    class Meta:
        model = models.EverydayResult
        fields = "__all__"


class PersonForm(MyForm,forms.ModelForm):
    class Meta:
        model = models.Person
        fields = '__all__'


class RewardForm(MyForm,forms.ModelForm):
    class Meta:
        model = models.Reward
        fields = '__all__'


class Admin(MyForm, forms.ModelForm):
    """管理员"""
    confirm_pwd = forms.CharField(label="确认密码",
                                  widget=forms.PasswordInput
                                  )

    class Meta:
        model = models.Admin
        fields = ["username", "password"]
        widgets = {
            "password": forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        """密码加密"""
        pwd = self.cleaned_data.get('password')
        md5_pwd = mymd5(pwd)
        return md5_pwd

    def clean_confirm_pwd(self):
        """从浏览器获取输入的密码和确认密码，加密后进行校验"""
        pwd = self.cleaned_data.get("password")
        confirm = mymd5(self.cleaned_data.get("confirm_pwd"))
        if confirm != pwd:
            raise ValidationError("密码不一致")
        return confirm


class AdminReset(Admin):
    """用户名在密码重置时，显示但不可修改"""
    username = forms.CharField(disabled=True, label="用户名")

    def clean_password(self):
        """密码加密"""
        pwd = self.cleaned_data.get('password')
        md5_pwd = mymd5(pwd)
        # 当前密码与数据库中密码校验，不允许重置密码和原密码一致
        exists = models.Admin.objects.filter(id=self.instance.pk, password=pwd).exists()
        if exists:
            raise ValidationError("重置密码不能和原密码一致")
        return md5_pwd


class Login(MyForm, forms.ModelForm):
    """登录"""
    code_str = forms.CharField(label="输入验证码",
                               widget=forms.TextInput(attrs={"class": "form-control"}),
                               )

    class Meta:
        model = models.Admin
        fields = ["username", "password"]
        widgets = {
            "password": forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        """密码加密"""
        pwd = self.cleaned_data.get('password')
        md5_pwd = mymd5(pwd)
        return md5_pwd
